package handler

import (
	"github.com/gin-gonic/gin"
	"img-text-mgr/model"
	"img-text-mgr/pkg"
	"strconv"
)

func Register(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	user := model.User{
		Tel:      tel,
		Password: pkg.Md5Str(password),
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "注册成功",
		})
		return
	}
}

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	if tel == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	var user model.User
	err := model.DB.Where("tel = ? and password = ?", tel, pkg.Md5Str(password)).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	} else {
		token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": token,
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.User{}).Count(&count)
	var user []model.User
	err := model.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"user":  user,
			},
		})
		return
	}
}
